#region License
/*
The MIT License

Copyright (c) 2008 Sky Morey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Threading;
using Native_;
using System.Collections.Specialized;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using Capture.Utility;
using System.Diagnostics;
namespace Capture.MME
{
    /// <summary>
    /// WaveCapturer
    /// </summary>
    public partial class WaveCapturer : IDisposable
    {
        private ManualResetEvent _stopEvent = new ManualResetEvent(false);
        private IWaveInfo _waveInfo;
        private DeviceInfo _device;
        private bool _dispatchOnWorkerThread;
        private bool _started;

        /// <summary>
        /// BehaviorVectorMask
        /// </summary>
        public enum BehaviorVectorMask
        {
            DispatchOnWorkerThread = 0x01
        }

        public WaveCapturer()
            : this(DeviceInfo.GetDefaultDevice()) { }
        public WaveCapturer(DeviceInfo device)
        {
            _device = device;
        }
        ~WaveCapturer() { Dispose(); }
        public virtual void Dispose()
        {
            if (_started)
                Stop();
            _stopEvent.Dispose(); _stopEvent = null;
            GC.SuppressFinalize(this);
        }

        public BitVector32 BehaviorVector = new BitVector32();

        public IWaveInfo WaveInfo
        {
            get { return _waveInfo; }
            private set
            {
                if (value == null)
                    throw new ArgumentNullException("value");
                _waveInfo = value;
            }
        }

        private void WorkerThread(object start)
        {
            if (BehaviorVector[(int)BehaviorVectorMask.DispatchOnWorkerThread])
                _dispatchOnWorkerThread = true;
            WaveInfo = ((Func<IWaveInfo>)start)();
            var grabber = new Grabber(WaveInfo, _dispatchOnWorkerThread);
            OnEnterWorkerThread();
            try
            {
                var format = new WaveFormat(44100, 16, _device.Channels);
                int bufferSize = (_device.Channels == 1 ? 8192 : 16384);
                int buffers = 2;
                Helper.Try(WindowsMultimedia.waveInOpen(out _wave, _device.Device, format, _bufferDelegate, 0, WindowsMultimedia.CALLBACK_FUNCTION));
                AllocateAllBuffers(bufferSize, buffers);
                Helper.Try(WindowsMultimedia.waveInStart(_wave));
                //
                if (_dispatchOnWorkerThread)
                {
                    Dispatcher.Run();
                    //while (!WaitHandle.WaitAll(new WaitHandle[] { _stopSignal }, 10, true))
                    while (!_stopEvent.WaitOne(10, true))
                    {
                        AdvanceBuffer();
                        grabber.Buffer(_currentBuffer.Data, _currentBuffer.Size);
                        _currentBuffer.AddBuffer();
                        Dispatcher.Run();
                    }
                    Dispatcher.ExitAllFrames();
                }
                else
                    while (!_stopEvent.WaitOne(0, true))
                    {
                        AdvanceBuffer();
                        grabber.Buffer(_currentBuffer.Data, _currentBuffer.Size);
                        _currentBuffer.AddBuffer();
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
            finally
            {
                // guaranteed exit
                OnExitWorkerThread();
            }
        }

        internal static void WaveInProc(IntPtr hdrvr, int uMsg, int dwUser, ref WindowsMultimedia.WaveHdr wavhdr, int dwParam2)
        {
            if (uMsg == WindowsMultimedia.MM_WIM_DATA)
                try
                {
                    var h = (GCHandle)wavhdr.dwUser;
                    var buffer = (Buffer)h.Target;
                    buffer.OnCompleted();
                }
                catch { }
        }

        #region Threading

        private Thread _workerThread;
        private IntPtr _wave;
        private WindowsMultimedia.WaveDelegate _bufferDelegate = new WindowsMultimedia.WaveDelegate(WaveInProc);

        public void Start(Func<IWaveInfo> start)
        {
            if (_device.Device < 0)
                return;
            if (_started)
                throw new InvalidOperationException("CaptureAlreadyStarted");
            _workerThread = new Thread(new ParameterizedThreadStart(WorkerThread))
            {
                Name = "WaveInWorker",
                Priority = ThreadPriority.Highest,
                IsBackground = true,
            };
            _workerThread.SetApartmentState(ApartmentState.MTA);
            _workerThread.Start(start);
            _started = true;
        }

        public void Stop()
        {
            if (!_started)
                throw new InvalidOperationException("CaptureNotStarted");
            WaitForAllBuffers();
            _stopEvent.Set();
#if DEBUG
            _workerThread.Join(); _workerThread = null;
#else
            _workerThread.Join(new TimeSpan(0, 0, 10)); _workerThread = null;
#endif
            Release();
            _started = false;
        }

        private void Release()
        {
            FreeAllBuffers();
            if (_wave != IntPtr.Zero)
            {
                WindowsMultimedia.waveInClose(_wave); _wave = IntPtr.Zero;
            }
        }

        public event EventHandler EnterWorkerThread;

        protected virtual void OnEnterWorkerThread()
        {
            var enterWorkerThread = EnterWorkerThread;
            if (enterWorkerThread != null)
                enterWorkerThread(this, EventArgs.Empty);
        }

        public event EventHandler ExitWorkerThread;

        protected virtual void OnExitWorkerThread()
        {
            var exitWorkerThread = ExitWorkerThread;
            if (exitWorkerThread != null)
                exitWorkerThread(this, EventArgs.Empty);
        }

        #endregion

        #region Buffers

        private Buffer _buffers; // linked list
        private Buffer _currentBuffer;

        private void AllocateAllBuffers(int bufferSize, int buffers)
        {
            FreeAllBuffers();
            if (buffers > 0)
            {
                _buffers = new Buffer(_wave, bufferSize);
                _buffers.AddBuffer();
                var prevBuffer = _buffers;
                try
                {
                    for (int bufferIndex = 1; bufferIndex < buffers; bufferIndex++)
                    {
                        var buffer = new Buffer(_wave, bufferSize);
                        buffer.AddBuffer();
                        prevBuffer.Next = buffer;
                        prevBuffer = buffer;
                    }
                }
                finally { prevBuffer.Next = _buffers; }
                _currentBuffer = _buffers;
            }
        }

        private void FreeAllBuffers()
        {
            _currentBuffer = null;
            if (_buffers != null)
            {
                var firstBuffer = _buffers;
                _buffers = null;
                var buffer = firstBuffer;
                do
                {
                    var nextBuffer = buffer.Next;
                    buffer.Dispose();
                    buffer = nextBuffer;
                } while (buffer != firstBuffer);
            }
        }

        private void AdvanceBuffer()
        {
            _currentBuffer = _currentBuffer.Next;
            _currentBuffer.WaitFor();
        }

        private void WaitForAllBuffers()
        {
            if (_wave != IntPtr.Zero)
                WindowsMultimedia.waveInReset(_wave);
            if (_buffers == null)
                return;
            var buffer = _buffers;
            while (buffer.Next != _buffers)
            {
                buffer.WaitFor();
                buffer = buffer.Next;
            }
        }

        #endregion
    }
}
